/*
 * PLyPlan类
 *
 * src/pl/plpython/plpy_planobject.c
 */

#include "postgres.h"

#include "plpy_cursorobject.h"
#include "plpy_elog.h"
#include "plpy_planobject.h"
#include "plpy_spi.h"
#include "plpython.h"
#include "utils/memutils.h"

static void fc_PLy_plan_dealloc(PyObject *fc_arg);
static PyObject *fc_PLy_plan_cursor(PyObject *fc_self, PyObject *fc_args);
static PyObject *fc_PLy_plan_execute(PyObject *fc_self, PyObject *fc_args);
static PyObject *fc_PLy_plan_status(PyObject *fc_self, PyObject *fc_args);

static char PLy_plan_doc[] = "Store a PostgreSQL plan";

static PyMethodDef PLy_plan_methods[] = {
	{"cursor", fc_PLy_plan_cursor, METH_VARARGS, NULL},
	{"execute", fc_PLy_plan_execute, METH_VARARGS, NULL},
	{"status", fc_PLy_plan_status, METH_VARARGS, NULL},
	{NULL, NULL, 0, NULL}
};

static PyTypeObject PLy_PlanType = {
	PyVarObject_HEAD_INIT(NULL, 0)
	.tp_name = "PLyPlan",
	.tp_basicsize = sizeof(PLyPlanObject),
	.tp_dealloc = fc_PLy_plan_dealloc,
	.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
	.tp_doc = PLy_plan_doc,
	.tp_methods = PLy_plan_methods,
};

void PLy_plan_init_type(void)
{
	if (PyType_Ready(&PLy_PlanType) < 0)
		elog(ERROR, "could not initialize PLy_PlanType");
}

PyObject * PLy_plan_new(void)
{
	PLyPlanObject *fc_ob;

	if ((fc_ob = PyObject_New(PLyPlanObject, &PLy_PlanType)) == NULL)
		return NULL;

	fc_ob->plan = NULL;
	fc_ob->nargs = 0;
	fc_ob->types = NULL;
	fc_ob->values = NULL;
	fc_ob->args = NULL;
	fc_ob->mcxt = NULL;

	return (PyObject *) fc_ob;
}

bool is_PLyPlanObject(PyObject *fc_ob)
{
	return fc_ob->ob_type == &PLy_PlanType;
}

static void fc_PLy_plan_dealloc(PyObject *fc_arg)
{
	PLyPlanObject *fc_ob = (PLyPlanObject *) fc_arg;

	if (fc_ob->plan)
	{
		SPI_freeplan(fc_ob->plan);
		fc_ob->plan = NULL;
	}
	if (fc_ob->mcxt)
	{
		MemoryContextDelete(fc_ob->mcxt);
		fc_ob->mcxt = NULL;
	}
	fc_arg->ob_type->tp_free(fc_arg);
}


static PyObject * fc_PLy_plan_cursor(PyObject *fc_self, PyObject *fc_args)
{
	PyObject   *fc_planargs = NULL;

	if (!PyArg_ParseTuple(fc_args, "|O", &fc_planargs))
		return NULL;

	return PLy_cursor_plan(fc_self, fc_planargs);
}


static PyObject * fc_PLy_plan_execute(PyObject *fc_self, PyObject *fc_args)
{
	PyObject   *fc_list = NULL;
	long		fc_limit = 0;

	if (!PyArg_ParseTuple(fc_args, "|Ol", &fc_list, &fc_limit))
		return NULL;

	return PLy_spi_execute_plan(fc_self, fc_list, fc_limit);
}


static PyObject * fc_PLy_plan_status(PyObject *fc_self, PyObject *fc_args)
{
	if (PyArg_ParseTuple(fc_args, ":status"))
	{
		Py_INCREF(Py_True);
		return Py_True;
		/* 返回 PyLong_FromLong(self->status); */
	}
	return NULL;
}
